package cn.jb698.codec.msm.generator.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CodecDbConnectionUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(CodecDbConnectionUtils.class);
	
	public static final String DB_DIALECT_ORACLE = "oracle";
	public static final String DB_DIALECT_MYSQL = "mysql";

	/**
	 * 获取数据库本地化信息
	 * @param connection
	 * @return
	 * @throws SQLException
	 */
	public static String getDialectByConnection(Connection connection) throws SQLException{
		String rtStr = null ;
		rtStr = connection.getMetaData().getDatabaseProductName();
		logger.debug("DatabaseProductName:" + rtStr );
		if(DB_DIALECT_MYSQL.equalsIgnoreCase(rtStr)){
			rtStr = DB_DIALECT_MYSQL ;
		}else if (DB_DIALECT_ORACLE.equalsIgnoreCase(rtStr)){
			rtStr = DB_DIALECT_ORACLE ;
		}else{
			rtStr = rtStr.toLowerCase();
		}
		return rtStr ;
	}

	/**
	 * 获取数据库名称
	 * @param conection
	 * @param dbdialect 
	 * @return
	 * @throws SQLException 
	 */
	public static String getDatabaseName(Connection conection) throws SQLException{
		String rtStr = null ;
		String dbdialect = getDialectByConnection(conection);
		if(DB_DIALECT_MYSQL.equals(dbdialect)){
			rtStr = conection.getCatalog();
		}else if (DB_DIALECT_ORACLE.equals(dbdialect)) {
		    rtStr = conection.getCatalog();
		}
		return rtStr ;
	}
	
	/**
	 * 获取所有表名列表
	 * @param connection
	 * @return
	 * @throws SQLException
	 */
	public static List<String> getAllTablesNameList(Connection connection ) throws SQLException{
		List<String> rtList = new ArrayList<String>();
		String dialectByConnection = getDialectByConnection(connection); 
		// mysql 获取所有表名的方式 
		if(DB_DIALECT_MYSQL.equals(dialectByConnection)) {
		    ResultSet rs = connection.getMetaData().getTables(null,null,"%",null);
		    while(rs.next()){
		        String tableName = rs.getString(3);
		        if(tableName != null && !"".equals(tableName)){
		            rtList.add(tableName);
		        }
		    }
		}else if (DB_DIALECT_ORACLE.equals(dialectByConnection)) {
		    String queryTableSql = "select table_name from user_tables"; 
		    ResultSet queryRst = connection.prepareStatement(queryTableSql).executeQuery();
		    while(queryRst.next()) {
		        String tmp_tableName = queryRst.getString(1);
		        rtList.add(tmp_tableName);
		    }
		}
		return rtList ;
	}

}
